package sis.studentinfo;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

abstract public class Session implements Comparable<Session>,
										Iterable<Student>,
										java.io.Serializable {
	private ArrayList<Student> allStudents = new ArrayList<Student>();
	private Date startDate;
	private int numberOfCredits;
	private URL url;
	private static int count;
	private Course course;
	/**
	 * 
	 * @param department 
	 * @param number   
	 * @param startDate 
	 */
	protected Session(Course course, Date startDate) {
		this.course = course;
		this.startDate = startDate;
	}
	private static void incrementCount() {
		count++;
	}
	public String getDepartment(){
		return course.getDepartment();
	}
	public String getNumber(){
		return course.getNumber();
	}
	public int getNumberOfStudents(){
		return allStudents.size();
	}
	public void enroll(Student student){
		student.addCredits(numberOfCredits);
		allStudents.add(student);
	}
	public void setNumberOfCredits(int numberOfCredits) {
		this.numberOfCredits = numberOfCredits;
	}
	public ArrayList<Student> getAllStudents() {
		return allStudents;
	}
	public Student get(int index){
		return allStudents.get(index);
	}
    /**
     * 
     * @return Date the last date of the course session
     */
	public Date getEndDate(){
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(startDate);
		int numberOfDays = getSessionLength()*7 - 3;
		calendar.add(Calendar.DAY_OF_YEAR, numberOfDays);
		return calendar.getTime();
	}
	public static void resetCount() {
		count = 0;
		
	}
	public static int getCount() {
		return count;
	}
	public static CourseSession create(Course course,Date startDate){
		incrementCount();
		return new CourseSession(course, startDate);
	}
	@Override
	public int compareTo(Session that) {
		// TODO Auto-generated method stub
		
		int compare = this.getDepartment().compareTo(that.getDepartment());
		if (compare == 0)
			compare = this.getNumber().compareTo(that.getNumber());
		return compare;
	}
	
	protected Date getStartDate() {
		return startDate;
	}
	public void setUrl(String urlString) throws SessionException {
		try {
			this.url = new URL(urlString);
		} catch (MalformedURLException e) {
			log(e);
			throw new SessionException(e);
		}
		
	}
	private void log(MalformedURLException e) {
		e.printStackTrace();
	}
	public URL getUrl() {
		return url;
	}
	abstract protected int getSessionLength();
	public int getNumberOfCredits() {
		return numberOfCredits;
	}
}
